package com.yulang.security.core.handler;

import com.alibaba.fastjson.JSONObject;
import com.yulang.security.BaseResult;
import com.yulang.security.core.listener.AuthenticationSuccessListener;
import com.yulang.security.core.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义成功处理器，响应json 或者 跳转页面
 */
@Component
public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired(required = false)
    private AuthenticationSuccessListener successListener;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        if(successListener!=null){
            successListener.successListener(request,response,authentication);
        }
        if(securityProperties.getAuthentication().isResponseJson()){
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSONObject.toJSONString(BaseResult.ok("认证成功")));
            response.getWriter().flush();
        }else{
            super.onAuthenticationSuccess(request,response,authentication);
        }

    }
}
